/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package at.fhj;

import at.fhj.itm.metadata.MetaDataException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


/**
 *
 * @author Seucht
 */
public class Application
{
    private static Connection connection;
    private static final String CONNECTION_STRING =
            "jdbc:postgresql://127.0.0.1/postgres";

    private static Application instance;

    private Application()
    {

    }

    public static void init()
    {
        getConnection();
    }

    public static void shutdown()
    {
        if(connection != null)
        {
            try
            {
                connection.close();
            }
            catch (SQLException ex){}
            connection = null;
        }
    }
    public static Application getInstance()
    {
        if(instance == null)
        {
            instance = new Application();
        }
        return instance;
    }
    public static  boolean hasConnection()
    {
        return connection != null;
    }
    public static void closeConnection()
    {
        try
        {
            if(connection != null)
            {
                connection.close();
            }
            connection = null;
        }
        catch(Exception ex)
        {

        }
    }
    public static synchronized Connection getConnection()
    {
        return getConnection(CONNECTION_STRING);
    }

    public static synchronized Connection getConnection(String conenctionStr)
    {
        if (connection == null)
        {
            try
            {
                Class.forName("org.postgresql.Driver");
                Properties props = new Properties();
                props.setProperty("user", "postgres");
                props.setProperty("password", "postgres");

                connection = DriverManager.getConnection(conenctionStr, props);
            }
            catch (ClassNotFoundException ex)
            {
                throw  new MetaDataException("Error loading JDBC driver class",ex);
            }
            catch (SQLException ex)
            {
                throw  new MetaDataException("Error creating connection",ex);
            }

        }
        return connection;
    }
}
